package com.example.courseservice.controller;

import com.example.courseservice.entity.course;
import com.example.courseservice.entity.courseInstructor;
import com.example.courseservice.entity.courseChapter;
import com.example.courseservice.entity.courseware;
import com.example.courseservice.service.CourseInstructorService;
import com.example.courseservice.service.CourseService;
import com.example.courseservice.service.ChapterService;
import com.example.courseservice.service.CWareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.stream.Collectors;
import java.util.UUID;

@Controller
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private CourseService courseService;
    @Autowired
    private CourseInstructorService courseInstructorService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private CWareService cWareService;

    @PostMapping(value = "/api/courses", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String createCourse(@RequestBody Map<String, Object> req) {
        course c = new course();
        c.setTitle((String) req.get("title"));
        c.setDescription((String) req.get("description"));
//        c.setCover_url((String) req.get("coverUrl"));
        Object createdBy = req.get("createdBy");
        c.setCreated_by((int)createdBy);
        c.setStatus(1);
        courseService.save(c);

        courseInstructor ci=new courseInstructor();
        ci.setCourseId(c.getId());
        ci.setTeacherId((int)createdBy);
        courseInstructorService.save(ci);
        return "ok";
    }

    @GetMapping("/api/coursesinfo")
    @ResponseBody
    public List<Map<String, Object>> listCoursesByCreator(@RequestParam("createdBy") int createdBy) {

        List<course> courses = courseService.lambdaQuery()
                .eq(course::getCreated_by, createdBy)
                .list();
//        System.out.println( "长度为 "+courses.size());

        return courses.stream().map(c -> {
            Map<String, Object> m = new HashMap<>();
            m.put("id", c.getId());
            m.put("title", c.getTitle());
            m.put("description", c.getDescription());
            m.put("status", c.getStatus());
            return m;
        }).collect(Collectors.toList());
    }

    @GetMapping("/api/chapters")
    @ResponseBody
    public List<Map<String, Object>> listChaptersByCourse(@RequestParam("courseId") int courseId) {
        List<courseChapter> chapters = chapterService.lambdaQuery()
                .eq(courseChapter::getCourse_id, courseId)
                .orderByAsc(courseChapter::getId)
                .list();
        return chapters.stream().map(c -> {
            Map<String, Object> m = new HashMap<>();
            m.put("id", c.getId());
            m.put("title", c.getTitle());
            m.put("courseId", c.getCourse_id());
            return m;
        }).collect(Collectors.toList());
    }

    @PostMapping(value = "/api/chapters", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String createChapter(@RequestBody Map<String, Object> req) {
        courseChapter chapter = new courseChapter();
        chapter.setTitle((String) req.get("title"));
        Object courseId = req.get("courseId");
        if (courseId instanceof Number) {
            chapter.setCourse_id(((Number) courseId).intValue());
        }
        chapterService.save(chapter);
        return "ok";
    }
    
    @DeleteMapping("/api/chapters/{chapterId}")
    @ResponseBody
    public String deleteChapter(@PathVariable int chapterId) {
        try {
            // 先删除该章节下的所有课件
            cWareService.lambdaUpdate()
                    .eq(courseware::getChapter_id, chapterId)
                    .remove();
            
            // 再删除章节
            chapterService.removeById(chapterId);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "删除失败: " + e.getMessage();
        }
    }

    @GetMapping("/api/courses")
    @ResponseBody
    public List<Map<String, Object>> listAllCourses() {
        List<course> courses = courseService.list();
        System.out.println("查询到的课程数量: " + courses.size());
        if (!courses.isEmpty()) {
            course firstCourse = courses.get(0);
            System.out.println("第一个课程详情:");
            System.out.println("  ID: " + firstCourse.getId());
            System.out.println("  Title: " + firstCourse.getTitle());
            System.out.println("  Created_by: " + firstCourse.getCreated_by());
            System.out.println("  Created_at: " + firstCourse.getCreated_at());
            System.out.println("  Status: " + firstCourse.getStatus());
            System.out.println("  Cover_url: " + firstCourse.getCover_url());
            System.out.println("  Category_id: " + firstCourse.getCategory_id());
        }
        return courses.stream().map(c -> {
            Map<String, Object> m = new HashMap<>();
            m.put("id", c.getId());
            m.put("title", c.getTitle());
            m.put("description", c.getDescription());
            m.put("status", c.getStatus());
            m.put("createdBy", c.getCreated_by());
            m.put("createdAt", c.getCreated_at());
            m.put("coverUrl", c.getCover_url());
            m.put("categoryId", c.getCategory_id());
            return m;
        }).collect(Collectors.toList());
    }

    // 保存课件信息到数据库
    @PostMapping("/api/material/save")
    @ResponseBody
    public String saveMaterial(@RequestBody Map<String, Object> materialData) {
        try {
            courseware cw = new courseware();
            cw.setCourse_id((Integer) materialData.get("courseId"));
            cw.setChapter_id((Integer) materialData.get("chapterId"));
            cw.setType((Integer) materialData.get("type"));
            cw.setName((String) materialData.get("name"));
            cw.setUrl((String) materialData.get("url"));
            cw.setSize_bytes((Integer) materialData.get("sizeBytes"));
            cw.setContent_type((String) materialData.get("contentType"));
            cw.setUploader_id((Integer) materialData.get("uploaderId"));
            cw.setCreated_at((String) materialData.get("createdAt"));

            cWareService.save(cw);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "保存失败: " + e.getMessage();
        }
    }

    // 获取章节课件列表
    @GetMapping("/api/course/{courseId}/chapter/{chapterId}/materials")
    @ResponseBody
    public List<Map<String, Object>> getChapterMaterials(@PathVariable int courseId, @PathVariable int chapterId) {
        List<courseware> materials = cWareService.lambdaQuery()
                .eq(courseware::getCourse_id, courseId)
                .eq(courseware::getChapter_id, chapterId)
                .orderByDesc(courseware::getCreated_at)
                .list();

        return materials.stream().map(m -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", m.getId());
            map.put("name", m.getName());
            map.put("url", m.getUrl());
            map.put("size_bytes", m.getSize_bytes());
            map.put("content_type", m.getContent_type());
            map.put("created_at", m.getCreated_at());
            return map;
        }).collect(Collectors.toList());
    }

    // 获取课件信息
    @GetMapping("/api/material/{materialId}/info")
    @ResponseBody
    public Map<String, Object> getMaterialInfo(@PathVariable int materialId) {
        try {
            courseware material = cWareService.getById(materialId);
            if (material == null) {
                return null;
            }

            Map<String, Object> result = new HashMap<>();
            result.put("id", material.getId());
            result.put("name", material.getName());
            result.put("url", material.getUrl());
            result.put("sizeBytes", material.getSize_bytes());
            result.put("contentType", material.getContent_type());
            result.put("createdAt", material.getCreated_at());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 删除课件数据库记录
    @DeleteMapping("/api/material/{materialId}/delete")
    @ResponseBody
    public String deleteMaterial(@PathVariable int materialId) {
        try {
            courseware material = cWareService.getById(materialId);
            if (material == null) {
                return "课件不存在";
            }

            // 删除数据库记录
            cWareService.removeById(materialId);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "删除失败: " + e.getMessage();
        }
    }

    // ========== 管理员专用接口 ==========
    
    // 管理员更新课程
    @PostMapping(value = "/admin/api/courses/{courseId}/update", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String adminUpdateCourse(@PathVariable int courseId, @RequestBody Map<String, Object> req) {
        try {
            course c = courseService.getById(courseId);
            if (c == null) {
                return "课程不存在";
            }

            if (req.containsKey("title")) {
                c.setTitle((String) req.get("title"));
            }
            if (req.containsKey("description")) {
                c.setDescription((String) req.get("description"));
            }
            if (req.containsKey("status")) {
                c.setStatus((Integer) req.get("status"));
            }

            courseService.updateById(c);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "更新课程失败: " + e.getMessage();
        }
    }

    // 管理员删除课程
    @DeleteMapping("/admin/api/courses/{courseId}")
    @ResponseBody
    public String adminDeleteCourse(@PathVariable int courseId) {
        try {
            course c = courseService.getById(courseId);
            if (c == null) {
                return "课程不存在";
            }

            // 删除课程-教师关联
            courseInstructorService.lambdaUpdate()
                    .eq(courseInstructor::getCourseId, courseId)
                    .remove();

            // 删除课程章节
            List<courseChapter> chapters = chapterService.lambdaQuery()
                    .eq(courseChapter::getCourse_id, courseId)
                    .list();
            for (courseChapter chapter : chapters) {
                // 删除章节下的课件
                cWareService.lambdaUpdate()
                        .eq(courseware::getChapter_id, chapter.getId())
                        .remove();
                // 删除章节
                chapterService.removeById(chapter.getId());
            }

            // 删除课程
            courseService.removeById(courseId);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "删除课程失败: " + e.getMessage();
        }
    }

    // 获取课程详细信息（包含学生数量和教师信息）
    @GetMapping("/admin/api/courses/{courseId}/details")
    @ResponseBody
    public Map<String, Object> getCourseDetails(@PathVariable int courseId) {
        try {
            course c = courseService.getById(courseId);
            if (c == null) {
                return new HashMap<>();
            }

            Map<String, Object> result = new HashMap<>();
            result.put("id", c.getId());
            result.put("title", c.getTitle());
            result.put("description", c.getDescription());
            result.put("status", c.getStatus());
            result.put("createdBy", c.getCreated_by());
            result.put("createdAt", c.getCreated_at());
            result.put("coverUrl", c.getCover_url());
            result.put("categoryId", c.getCategory_id());

            // 获取课程章节数量
            long chapterCount = chapterService.lambdaQuery()
                    .eq(courseChapter::getCourse_id, courseId)
                    .count();
            result.put("chapterCount", chapterCount);

            // 获取课程教师信息
            List<courseInstructor> instructors = courseInstructorService.lambdaQuery()
                    .eq(courseInstructor::getCourseId, courseId)
                    .list();
            result.put("instructorIds", instructors.stream()
                    .map(courseInstructor::getTeacherId)
                    .collect(Collectors.toList()));

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }
}
